package com.gxsyh.nantie.log.consumer.component;
import java.io.IOException;
import java.util.Date;

import com.gxsyh.nantie.commons.configure.rabbitmq.RabbitMQConfig;
import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.dto.SendLogResult;
import com.gxsyh.nantie.commons.utils.ByteArrayUtils;
import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.log.consumer.domain.TbLog;
import com.gxsyh.nantie.log.consumer.domain.TbUserLog;
import com.gxsyh.nantie.log.consumer.service.TbLogService;
import com.gxsyh.nantie.log.consumer.service.TbUserLogService;
import okhttp3.Response;
import okhttp3.ResponseBody;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.Resource;

/**
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/1/8
 * @time: 10:00
 * @Description:
 */

@Transactional
@Service
public class LogConsumer {

    @Resource
    TbLogService tbLogService;

    @Resource
    TbUserLogService tbUserLogService;

    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    @RabbitListener(queues = RabbitMQConfig.SEND_LOG_QUEUE)
    public void receive(Message message) throws IOException {
        SendLogResult sendLogResult = (SendLogResult) ByteArrayUtils.byteArrayToObject(message.getBody());
        TbLog tbLog=new TbLog();
        ResponseBody body = OkHttpClientUtil.getInstance().getData(LEAF_URL + "log").body();
        Long logId = Long.valueOf(body.string());
        TbUserLog tbUserLog=new TbUserLog();

        tbLog.setId(logId);
        tbLog.setCreatetime(new Date());
        tbLog.setLogInfo(sendLogResult.getUserId()+" "+sendLogResult.getUsername()+ " "+sendLogResult.getInfo());
        tbLogService.insterLog(tbLog);


        ResponseBody logid = OkHttpClientUtil.getInstance().getData(LEAF_URL + "logid").body();
        tbUserLog.setId(Long.valueOf(logid.string()));
        tbUserLog.setUserId(Long.valueOf(sendLogResult.getUserId()));
        tbUserLog.setLogId(logId);
        tbUserLogService.insterTbUserLog(tbUserLog);
    }



}
